package com.jy.api.okhttp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.jy.api.patient.dto.BingRenXXDto;
import com.jy.api.patient.dto.PatientIndexDto;
import com.jy.framework.base.entity.Result;
import com.jy.rhin.config.EmpiConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

/**
 * 旗云健康 数据客户端
 *
 * @ename wade.nie
 * @cname 聂敏
 * @email 550552699@qq.com
 * @date 2024/7/15
 */
@Slf4j
@Component("QyjkHealthdcClient")
public class QyjkHealthdcClient extends AbstractThirdClient {

    @Autowired
    private EmpiConfig empiConfig;

    public QyjkHealthdcClient(@Qualifier("okHttpTemplate") RestTemplate restTemplate) {
        super(restTemplate);
    }

    public EmpiConfig getEmpiConfig() {
        return empiConfig;
    }

    public void setEmpiConfig(EmpiConfig empiConfig) {
        this.empiConfig = empiConfig;
    }

    @Override
    public String name() {
        return "QyjkHealthdcClient";
    }

    /**
     * 添加或者更新患者信息
     *
     * @param bingRenXXDto
     * @return
     */
    public Result<String> insertOrUpdate(BingRenXXDto bingRenXXDto) {
        //接口文档 https://apifox.com/apidoc/shared-203d96ee-4cb0-45a6-9371-06ed78e30a3b/api-195100350
        String url = empiConfig.getUrl().getPatientInsertOrUpdatePath();
        String paramBody = JSON.toJSONString(bingRenXXDto);
        log.debug("发起远程http更新患者信息：{}=>{}", url, paramBody);
        JSONObject patientJsonParam = new JSONObject();
        patientJsonParam.put("name", bingRenXXDto.getBingRenXM());
        patientJsonParam.put("sex", bingRenXXDto.getXingBieDM());
        patientJsonParam.put("mobile", bingRenXXDto.getGuDingDH());
        patientJsonParam.put("gbname", bingRenXXDto.getJiaTingDZ());
        patientJsonParam.put("birthday", bingRenXXDto.getChuShengRQ());
        patientJsonParam.put("cardType", bingRenXXDto.getZhengJianLX());
        patientJsonParam.put("cardNo", bingRenXXDto.getZhengJianHM());
        patientJsonParam.put("marriageCode", bingRenXXDto.getHunYinZTMC());
        patientJsonParam.put("professionCode", bingRenXXDto.getZhiYeLBDM());
        patientJsonParam.put("educationLevel", bingRenXXDto.getXueLi());
        patientJsonParam.put("birthPlace", bingRenXXDto.getChuShengDi());
        patientJsonParam.put("nationalityCode", bingRenXXDto.getGuoJiDM());
        patientJsonParam.put("deathState", bingRenXXDto.getBingRenZT());
        //民族
        patientJsonParam.put("raceCode", bingRenXXDto.getMinZuDM());
        //籍贯
        patientJsonParam.put("nativePlace", bingRenXXDto.getJiGuan());
        patientJsonParam.put("aboBloodCode", bingRenXXDto.getXueXingDM());
        patientJsonParam.put("rhBloodCode", bingRenXXDto.getRhXXDM());
        patientJsonParam.put("residenceProvince", bingRenXXDto.getJuZhuDSFDM());
        patientJsonParam.put("residenceCity", bingRenXXDto.getJuZhuDSDM());
        patientJsonParam.put("residenceCounty", bingRenXXDto.getJuZhuDQDM());
        patientJsonParam.put("residenceTown", bingRenXXDto.getJuZhuDJDDM());
        patientJsonParam.put("residenceHouseNo", bingRenXXDto.getJuZhuDMPH());
        patientJsonParam.put("registeredProvince", bingRenXXDto.getHuKouSFDM());
        patientJsonParam.put("registeredCity", bingRenXXDto.getHuKouSDM());
        patientJsonParam.put("registeredCounty", bingRenXXDto.getHuKouQDM());
        patientJsonParam.put("registeredTown", bingRenXXDto.getHuKouJDDM());
        patientJsonParam.put("registeredHouseNo", bingRenXXDto.getHuKouDZ());
        patientJsonParam.put("height", bingRenXXDto.getShenGao());
        patientJsonParam.put("weight", bingRenXXDto.getTiZhong());
        String paramStr = patientJsonParam.toString();
        log.debug("request param: {}",paramStr);
        ResponseEntity<String> responseEntity = execute(url, null, HttpMethod.POST, MediaType.APPLICATION_JSON, patientJsonParam.toString(), Maps.newHashMap());
        String message = this.verify(responseEntity);
        if (StringUtils.isNotBlank(message)) {
            log.error("发起远程http更新患者信息：{}", message);
            return Result.fail(message);
        }
        JSONObject jsonObject = JSONObject.parseObject(responseEntity.getBody());
        String data = jsonObject.getString("data");
        return Result.success(data);
    }

    /**
     * @param zhengJianHM
     * @return
     */
    public Result<BingRenXXDto> patientQueryByIdCard(String zhengJianHM) {
        String url = empiConfig.getUrl().getPatientQueryByIdCardPath();
        log.debug("发起远程http通过身份证获得患者信息：{}=>{}", url, StringUtils.join(new Object[]{zhengJianHM}, ":"));
        Map<String, Object> uriVariables = Maps.newHashMap();
        uriVariables.put("zhengJianHM", zhengJianHM);
        ResponseEntity<String> responseEntity = execute(url, null, HttpMethod.GET, MediaType.APPLICATION_JSON, null, uriVariables);
        String message = this.verify(responseEntity);
        if (StringUtils.isNotBlank(message)) {
            log.error("发起远程http通过身份证获得患者信息：{}", message);
            return Result.fail(message);
        }
        JSONObject jsonObject = JSONObject.parseObject(responseEntity.getBody());
        JSONObject data = jsonObject.getJSONObject("data");
        BingRenXXDto object = data.toJavaObject(BingRenXXDto.class);
        return Result.success(object);
    }

    /**
     * 查询患者信息
     *
     * @param hyzk     婚姻状况
     * @param swbj     死亡标记
     * @param qscsrq   出生日期-查询开始时间
     * @param zzcsrq   出生日期-查询结束时间
     * @param xbdm     性别代码
     * @param from     开始记录
     * @param maxCount 返回条数
     * @return
     */
    public Result<List<BingRenXXDto>> patientPageQuery(String hyzk, String swbj, String qscsrq, String zzcsrq, String xbdm, Integer from, Integer maxCount) {
        String url = empiConfig.getUrl().getPatientPageQueryPath();
        log.debug("发起远程http查询患者信息：{}=>{}", url, StringUtils.join(new Object[]{hyzk, swbj, qscsrq, zzcsrq, xbdm, from, maxCount}, ":"));
        Map<String, Object> uriVariables = Maps.newHashMap();
        uriVariables.put("hyzk", hyzk);
        uriVariables.put("swbj", swbj);
        uriVariables.put("qscsrq", qscsrq);
        uriVariables.put("zzcsrq", zzcsrq);
        uriVariables.put("xbdm", xbdm);
        if (from == null) {
            uriVariables.put("from", 1);
        } else {
            uriVariables.put("from", from);
        }
        if (maxCount == null) {
            uriVariables.put("maxCount", 10);
        } else {
            uriVariables.put("maxCount", maxCount);
        }
        ResponseEntity<String> responseEntity = execute(url, null, HttpMethod.GET, MediaType.APPLICATION_JSON, null, uriVariables);
        String message = this.verify(responseEntity);
        if (StringUtils.isNotBlank(message)) {
            log.error("发起远程http查询患者信息：{}", message);
            return Result.fail(message);
        }
        JSONObject jsonObject = JSONObject.parseObject(responseEntity.getBody());
        JSONObject data = jsonObject.getJSONObject("data");
        JSONArray list = data.getJSONArray("list");
        if (list != null && list.size() > 0) {
            List<BingRenXXDto> object = list.toJavaList(BingRenXXDto.class);
            return Result.success(object);
        }
        return Result.success();
    }

    /**
     * 查询交叉索引
     *
     * @param eid   源业务ID
     * @param appId 目标系统
     * @return
     */
    public Result<List<BingRenXXDto>> pix(String eid, String appId) {
        String url = empiConfig.getUrl().getIdentifierQueryPath();
        log.debug("发起远程http获得交叉索引：{}=>{}", url, StringUtils.join(new Object[]{eid, appId}, ":"));
        Map<String, Object> uriVariables = Maps.newHashMap();
        uriVariables.put("eid", eid);
        uriVariables.put("appId", appId);
        ResponseEntity<String> responseEntity = execute(url, null, HttpMethod.GET, MediaType.APPLICATION_JSON, null, uriVariables);
        String message = this.verify(responseEntity);
        if (StringUtils.isNotBlank(message)) {
            log.error("发起远程http获得交叉索引：{}", message);
            return Result.fail(message);
        }
        JSONObject jsonObject = JSONObject.parseObject(responseEntity.getBody());
        JSONArray data = jsonObject.getJSONArray("data");
        if (data != null && data.size() > 0) {
            List<BingRenXXDto> object = data.toJavaList(BingRenXXDto.class);
            return Result.success(object);
        }
        return Result.success();
    }

    public Result<List<PatientIndexDto>> patientIndexs(String xingMing, Integer type, String zhengJianHM) {
        String url = empiConfig.getUrl().getPatientIndex();
        log.info("发起远程http获得病人索引关系：{}=>{}", url, StringUtils.join(new Object[]{xingMing, type, zhengJianHM}, ":"));
        Map<String, Object> uriVariables = Maps.newHashMap();
        uriVariables.put("xingMing", xingMing);
        uriVariables.put("type", type);
        uriVariables.put("zhengJianHM", zhengJianHM);

        ResponseEntity<String> responseEntity = execute(url, null, HttpMethod.GET, MediaType.APPLICATION_JSON, null, uriVariables);

        String message = this.verify(responseEntity);
        if (StringUtils.isNotBlank(message)) {
            log.error("发起远程http获得病人索引关系：{}", message);
            return Result.fail(message);
        }

        JSONObject jsonObject = JSONObject.parseObject(responseEntity.getBody());
        JSONArray data = jsonObject.getJSONArray("data");
        if (data != null && data.size() > 0) {
            List<PatientIndexDto> object = data.toJavaList(PatientIndexDto.class);
            return Result.success(object);
        }
        return Result.success();
    }

    public Result<PatientIndexDto> patientIndex(String empi) {
        Result<List<PatientIndexDto>> result = this.patientIndexs(null, 2, empi);
        if (!result.isSuccess()) {
            return Result.fail(result.getMsg());
        }
        if (CollectionUtils.isEmpty(result.getData())) {
            return Result.success(null);
        }
        return Result.success(result.getData().get(0));
    }

    public Result<BingRenXXDto> patientInfo(String patientId) {
        String url = empiConfig.getUrl().getPatientInfo();
        log.info("发起远程http获得病人详细信息：{}=>{}", url, patientId);
        Map<String, Object> uriVariables = Maps.newHashMap();
        uriVariables.put("patientId", patientId);
        ResponseEntity<String> responseEntity = execute(url, null, HttpMethod.GET, MediaType.APPLICATION_JSON, null, uriVariables);

        String message = this.verify(responseEntity);
        if (StringUtils.isNotBlank(message)) {
            log.error("发起远程http获得病人详细信息：{}", message);
            return Result.fail(message);
        }

        JSONObject jsonObject = JSONObject.parseObject(responseEntity.getBody());
        JSONObject data = jsonObject.getJSONObject("data");
        BingRenXXDto object = data.toJavaObject(BingRenXXDto.class);
        return Result.success(object);
    }

    private String verify(ResponseEntity<String> responseEntity) {
        if (!super.isSuccess(responseEntity)) {
            return "请求状态不成功：" + responseEntity.getStatusCode();
        }

        String body = responseEntity.getBody();
        log.debug("response body {}", body);
        JSONObject jsonObject = JSONObject.parseObject(body);

        String code = jsonObject.getString("code");
        String msg = jsonObject.getString("msg");
        if (!this.isSuccess(code)) {
            return StringUtils.join("业务状态不成功：", code, ":", msg);
        }
        return null;
    }

    private boolean isSuccess(String code) {
        return "1".equals(code);
    }
}
